//
//  IOTEquipmentVC.m
//  QoilPublic
//
//  Created by SunChao on 2018/4/13.
//  Copyright © 2018年 孙超. All rights reserved.
//


#import "IOTEquipmentVC.h"
#import "EquipmentCell.h"
#import "CoordinatesModel.h"
typedef NS_ENUM(NSInteger, WorkStatus) {
    WorkStatusUnknown          = -1,
    WorkStatusALL              = 0,
    WorkStatusWorked           = 1,
    WorkStatusRest             = 2,
};
@interface IOTEquipmentVC ()<UITableViewDelegate,UITableViewDataSource,AMapSearchDelegate>



@property (nonatomic,strong)NSMutableArray *workArr;
@property (nonatomic,strong)NSMutableArray *restArr;
@property (nonatomic,strong)NSMutableArray *tmpArr;
@property (nonatomic,assign)NSInteger status;
@property (nonatomic,strong)AMapSearchAPI *search;
@end

@implementation IOTEquipmentVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
     [self requestALLDeviceData];
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.tbView.delegate = self;
    self.tbView.dataSource = self;
    [self.tbView registerNib:[UINib nibWithNibName:@"EquipmentCell" bundle:nil] forCellReuseIdentifier:@"EquipmentCell"];
    
    UIView *view = [[UIView alloc ]initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
    view.backgroundColor = [UIColor whiteColor];
    NSArray *array = @[@"全部",@"工作中",@"熄火"];
    NSArray *selArr = @[@"全部B",@"工作中B",@"熄火B"];
    for (int i = 0; i<3; i++) {
        
        UIButton *button = [UIButton buttonWithType:0];
        button.frame = CGRectMake(10+i*(60+10),13, 60, 25);
        button.tag = 100+i;
        [button setTitle:[array objectAtIndex:i] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:[array objectAtIndex:i]] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:[selArr objectAtIndex:i]] forState:UIControlStateSelected];
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        button.layer.cornerRadius = 5.0f;
        button.layer.masksToBounds = YES;
        [view addSubview:button];
        if (button.tag == 100) {
            button.selected = YES;
        }
        
    }
    
    self.tbView.tableHeaderView = view;
   self.tbView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
}


- (void)buttonAction:(UIButton *)button{
    
    NSLog(@"tag:%ld",button.tag);
    for (int i = 100; i<103; i++) {
        UIButton *button =(UIButton *) [self.view viewWithTag:i];
        button.selected = NO;
    }
    
    button.selected =YES;
    switch (button.tag-100) {
        case 0:
        {
            _status = WorkStatusALL;
            
        }
            break;
        case 1:
        {
            _status = WorkStatusWorked;
           
        }
            break;
        case 2:
        {
            _status = WorkStatusRest;
            
        }
            break;
            
        default:
            break;
    }
    NSLog(@"%ld",self.tmpArr.count);
    [self.tbView reloadData];
    
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (_status == WorkStatusALL) {
        return self.tmpArr.count;
    }
    if (_status == WorkStatusWorked) {
        return self.workArr.count;
    }
    if (_status == WorkStatusRest) {
        return self.restArr.count;
    }
    return 0;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 189;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    EquipmentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EquipmentCell"];

    if (_status == WorkStatusALL) {
         [cell setCellWithData:[self.tmpArr objectAtIndex:indexPath.row]];
    }
    if (_status == WorkStatusWorked) {
        [cell setCellWithData:[self.workArr objectAtIndex:indexPath.row]];
    }
    if (_status == WorkStatusRest) {
        [cell setCellWithData:[self.restArr objectAtIndex:indexPath.row]];
    }
   
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
    
}
- (void)requestALLDeviceData{
    
    
    NSString *url = [QParamService urlWithIOTAction:@"map/deviceList"];
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setObject:[QParamService getToken] forKey:@"token"];
    [param setObject:@"0" forKey:@"pageNum"];
    [param setObject:@"0" forKey:@"pageSize"];
     [param setObject:@"-1" forKey:@"workStatus"];
    [[QHttpManager sharedManager] POST:url parameterMD5jm:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if (error) {
            
            NSLog(@"error:%@",basModel.errMsg);
            
            return ;
            
        }
        
        if([basModel.result isEqualToString:@"success"]){
            
            NSLog(@"dic:%@",basModel.items);
            
            NSArray *array = basModel.items;
            for (NSDictionary *dic in array) {
                
                CoordinatesModel *model = [CoordinatesModel objectFromDict:dic];
                 [self.tmpArr addObject:model];
                [self addressResolutionWithLat:[model.lat floatValue] lng:[model.lng floatValue]];
               
            }
        }
        
    }];
}
- (void)addressResolutionWithLat:(CGFloat)lat lng:(CGFloat)lng{
    
    _search = [[AMapSearchAPI alloc] init];
    _search.delegate = self;
    AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
    
    regeo.location                    = [AMapGeoPoint locationWithLatitude:lat longitude:lng];
    regeo.requireExtension            = YES;
    [_search AMapReGoecodeSearch:regeo];
}
/* 逆地理编码回调. */

- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response

{
    
    
    
    if (response.regeocode !=nil )
        
    {
        
        NSLog(@"反向地理编码回调1:%@",response.regeocode.addressComponent.neighborhood);
        
        NSLog(@"反向地理编码回调2:%@",response.regeocode.addressComponent.adcode);
        
        NSLog(@"反向地理编码回调3:%@",response.regeocode.addressComponent.township);
        
        NSLog(@"反向地理编码回调4:%@",response.regeocode.addressComponent.towncode);
        
        NSLog(@"反向地理编码回调5:%@",response.regeocode.addressComponent.district);
        
        NSLog(@"反向地理编码回调6:%@",response.regeocode.formattedAddress);
        
        for (CoordinatesModel *model in self.tmpArr) {
            
            model.formattedAddress = response.regeocode.formattedAddress;
        }
        [self.workArr removeAllObjects];
        [self.restArr removeAllObjects];
        for (CoordinatesModel *model in self.tmpArr) {
            if ([model.workStatus isEqualToString:@"1"]) {
                [self.workArr addObject:model];
            }
        }
        for (CoordinatesModel *model in self.tmpArr) {
            if ([model.workStatus isEqualToString:@"0"]) {
                [self.restArr addObject:model];
            }
        }
       
        [_tbView reloadData];
        
    }
    
}

- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    NSLog(@"Error: %@", error);
}
ARRAY_INIT(workArr);
ARRAY_INIT(restArr);
ARRAY_INIT(tmpArr);
@end
